package com.bluedot.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bluedot.pojo.pack.ResultEntity;
import com.bluedot.pojo.vo.UserVO;
import com.bluedot.service.Token;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

public class GetUserFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 1.获取token
        String token = ((HttpServletRequest) request).getHeader("token");
        // 2.根据token获取Claims
        Claims tokenClaim = new Token().getTokenClaim(token);
        // 3.再获得JSON数据
        String subject = tokenClaim.getSubject();
        Map map = JSONObject.parseObject(subject, Map.class);
        // 4.获得userVo
        HttpSession session = ((HttpServletRequest) request).getSession();
        UserVO user = (UserVO) session.getAttribute("user");
        // 5.写入响应包中
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(JSON.toJSONString(ResultEntity.successWithData(user)));
        response.getWriter().flush();
    }
}
